import { useState, useEffect, useRef } from 'preact/hooks';
import { invoke } from '@tauri-apps/api/core';
import { listen } from '@tauri-apps/api/event';
import './App.css';
import { 
  Typography, 
  TextField, 
  Button, 
  Container, 
  Box, 
  Paper, 
  Grid, 
  Slider, 
  Alert, 
  LinearProgress, 
  List,
  ListItem,
  ListItemText,
} from '@mui/material';
import { FolderOpen, CloudDownload } from '@mui/icons-material';

interface DownloadProgress {
  playlist_index: number;
  playlist_count: number;
  title: string;
  progress: number;
  status: string;
}

export function App() {
  const [, setInitialized] = useState(false);
  const [inputText, setInputText] = useState('');
  // 移除不再使用的播放列表元数据状态
  const [isLoading, setIsLoading] = useState(false);
  const [isDownloading, setIsDownloading] = useState(false);
  const [downloadProgress, setDownloadProgress] = useState<DownloadProgress | null>(null);
  const [downloadedFiles, setDownloadedFiles] = useState<string[]>([]);
  const [outputDir, setOutputDir] = useState('');
  const [targetLoudness, setTargetLoudness] = useState(-5);
  const [error, setError] = useState('');
  const [statusMessage, setStatusMessage] = useState('准备就绪');
  const [logs, setLogs] = useState<string[]>([]);
  const logsEndRef = useRef<HTMLDivElement>(null);
  // Ref to track previous progress for logging
  const prevProgressRef = useRef(0);

  // Initialize the app
  useEffect(() => {
    async function init() {
      try {
        await invoke('initialize');
        setInitialized(true);
        addLog('应用初始化完成');
      } catch (e) {
        setError(`Failed to initialize: ${e}`);
        addLog(`初始化失败: ${e}`);
      }
    }
    init();
  }, []);

  // Auto-scroll logs to bottom
  useEffect(() => {
    // if (logsEndRef.current) {
    //   logsEndRef.current.scrollIntoView({ behavior: 'smooth' });
    // }
  }, [logs]);

  // Add a log message with limit to prevent memory issues
  const addLog = (message: string) => {
    // const timestamp = new Date().toLocaleTimeString();
    setLogs(() => {
      // const newLogs = [...prevLogs, `[${timestamp}] ${message}`];
      // return newLogs;
      return [message];
    });
  };

  // Poll for progress updates when downloading or processing
  useEffect(() => {
    if (!isDownloading) return;

    const interval = setInterval(async () => {
      if (isDownloading) {
        try {
          const progress = await invoke<DownloadProgress>('get_download_progress');
          setDownloadProgress(progress);
          
          // 更新状态信息条
          const statusMsg = `下载中: ${progress.title} (${Math.round(progress.progress * 100)}%)`;
          setStatusMessage(statusMsg);
          
          // Only log progress updates when there's a significant change (every 10%)
          const roundedProgress = Math.round(progress.progress * 10);
          if (progress.progress > 0 && roundedProgress !== prevProgressRef.current) {
            addLog(statusMsg);
            prevProgressRef.current = roundedProgress;
          }
          
          if (progress.status === 'Download complete') {
            setIsDownloading(false);
            setStatusMessage('下载完成');
            addLog('下载完成');
          }
        } catch (e) {
          console.error('Failed to get download progress:', e);
          addLog(`获取下载进度失败: ${e}`);
        }
      }
    }, 500);

    return () => clearInterval(interval);
  }, [isDownloading]);

  // Listen for log events from backend
  useEffect(() => {
    const unsubscribe = listen('log_event', (event) => {
      addLog(event.payload as string);
    });

    return () => unsubscribe.then(unsub => unsub());
  }, [addLog]);

  // Browse for output directory
  const handleBrowseDirectory = async () => {
    try {
      const selected = await invoke<string>('browse_directory');
      
      if (selected) {
        setOutputDir(selected);
        await invoke('set_output_directory', { path: selected });
        addLog(`输出目录已设置: ${selected}`);
      }
    } catch (e) {
      setError(`Failed to select directory: ${e}`);
      addLog(`选择目录失败: ${e}`);
    }
  };

  // Process and download all items from the input text
  const handleDownload = async () => {
    if (!inputText.trim()) {
      setError('请输入URL或歌曲名称');
      return;
    }

    setError('');
    setIsLoading(true);
    setIsDownloading(true);
    setStatusMessage('开始解析输入内容...');
    addLog('开始解析输入内容');
    
    try {
      // 将输入文本分割成行，过滤掉空行
      const lines = inputText.split('\n').filter(line => line.trim() !== '');
      addLog(`发现 ${lines.length} 个项目需要处理`);
      
      // 创建一个累积下载文件的数组
      let allDownloadedFiles: string[] = [];
      
      // 逐行处理，每行可以是URL或歌曲名称
      for (let i = 0; i < lines.length; i++) {
        const line = lines[i].trim();
        
        // 判断是URL还是歌曲名称
        const isUrl = line.startsWith('http://') || line.startsWith('https://');
        addLog(`处理第 ${i+1}/${lines.length} 项: ${isUrl ? 'URL' : '歌曲名称'}`);
        addLog(`内容: ${line}`);
        
        try {
          // 调用后端下载，无论是URL还是歌曲名称，后端会自动区分处理
          // 修复参数名从 output_dir 到 outputDir 以匹配后端要求
          const files = await invoke<string[]>('download_media', { url: line, outputDir: outputDir });
          
          // 添加到总下载文件列表
          allDownloadedFiles = [...allDownloadedFiles, ...files];
          
          // // 记录下载结果
          // if (files.length > 0) {
          //   addLog(`成功下载 ${files.length} 个文件`);
          //   files.forEach(file => {
          //     addLog(`文件: ${file.split('/').pop()}`);
          //   });
          // } else {
          //   addLog(`未找到可下载的文件: ${line}`);
          // }
        } catch (e) {
          // 单个项目下载失败，记录错误但继续下一个
          addLog(`下载失败: ${line} - ${e}`);
        }
      }
      
      // 更新下载文件列表
      setDownloadedFiles(allDownloadedFiles);
      setStatusMessage('所有下载任务分发完成');
      addLog(`所有下载任务分发完成，共需要下载 ${allDownloadedFiles.length} 个文件`);
      
    } catch (e) {
      setError(`下载过程中发生错误: ${e}`);
      setStatusMessage('下载失败');
      addLog(`下载过程中发生错误: ${e}`);
    } finally {
      setIsLoading(false);
      setIsDownloading(false);
    }
  };

  return (
    <Container maxWidth="md" sx={{ paddingTop: 4, paddingBottom: 4 }}>
      <Typography variant="h3" component="h1" gutterBottom align="center">
        Bootleg Link NG
      </Typography>
      
      {/* 状态信息条 */}
      <Paper 
        elevation={2} 
        sx={{ 
          p: 2, 
          mb: 2, 
          display: 'flex', 
          alignItems: 'center',
          bgcolor: isDownloading ? 'info.dark' : 'success.dark'
        }}
      >
        <Typography variant="subtitle1" sx={{ fontWeight: 'bold', color: 'white' }}>
          状态: {statusMessage}
        </Typography>
      </Paper>
      
      {error && (
        <Alert severity="error" sx={{ mb: 2 }}>
          {error}
        </Alert>
      )}
      
      <Paper elevation={3} sx={{ p: 3, mb: 3 }}>
        <Typography variant="h5" component="h2" gutterBottom>
          Settings
        </Typography>
        <Box sx={{ mb: 2 }}>
          <Typography variant="subtitle1" gutterBottom>
            Output Directory
          </Typography>
          <Grid container spacing={2}>
            <Grid item xs={9}>
              <TextField
                fullWidth
                value={outputDir}
                placeholder="Select an output directory"
                InputProps={{ readOnly: true }}
              />
            </Grid>
            <Grid item xs={3}>
              <Button 
                variant="contained" 
                color="primary" 
                onClick={handleBrowseDirectory}
                startIcon={<FolderOpen />}
                fullWidth
                sx={{ height: '100%' }}
              >
                Browse
              </Button>
            </Grid>
          </Grid>
        </Box>
        
        <Box sx={{ mb: 2 }}>
          <Typography variant="subtitle1" gutterBottom>
            Target Loudness: {targetLoudness} LUFS
          </Typography>
          <Slider
            value={targetLoudness}
            onChange={(_, value) => setTargetLoudness(value as number)}
            min={-5}
            max={-5}
            step={0.5}
            marks
            valueLabelDisplay="auto"
          />
        </Box>
      </Paper>
      
      <Paper elevation={3} sx={{ p: 3, mb: 3 }}>
        <Typography variant="h5" component="h2" gutterBottom>
          批量下载
        </Typography>
        <Box sx={{ mb: 2 }}>
          <Typography variant="subtitle1" gutterBottom>
            输入URL或歌曲名称（每行一个）
          </Typography>
          <TextField
            fullWidth
            multiline
            rows={6}
            value={inputText}
            onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
              const target = e.currentTarget;
              if (target) {
                setInputText(target.value);
              }
            }}
            placeholder="输入URL或歌曲名称，每行一个。例如：
https://www.youtube.com/watch?v=dQw4w9WgXcQ
Never Gonna Give You Up
https://soundcloud.com/..."
          />
        </Box>
        
        <Button 
          variant="contained" 
          color="primary" 
          onClick={handleDownload}
          disabled={isDownloading || !outputDir}
          startIcon={<CloudDownload />}
          fullWidth
          sx={{ mb: 2 }}
        >
          开始下载
        </Button>
        
        {isLoading && (
          <LinearProgress sx={{ mb: 2 }} />
        )}
        
        {isDownloading && downloadProgress && (
          <Box sx={{ mt: 2 }}>
            <Typography variant="subtitle1">
              下载中: {downloadProgress.title}
            </Typography>
            <Typography variant="body2">
              {downloadProgress.playlist_index} of {downloadProgress.playlist_count} ({downloadProgress.status})
            </Typography>
            <LinearProgress 
              variant="determinate" 
              value={downloadProgress.progress * 100} 
              sx={{ mt: 1, mb: 2 }}
            />
          </Box>
        )}
      </Paper>
      
      {/* 日志显示区域 */}
      <Paper elevation={3} sx={{ p: 3, mb: 3 }}>
        <Typography variant="h5" component="h2" gutterBottom>
          日志
        </Typography>
        <Box 
          sx={{ 
            maxHeight: 'auto', 
            overflowY: 'auto',
            bgcolor: '#000000',
            p: 2,
            borderRadius: 1,
            fontFamily: 'monospace',
            fontSize: '0.9rem'
          }}
        >
          {logs.length === 0 ? (
            <Typography variant="body2" color="textSecondary">
              暂无日志记录
            </Typography>
          ) : (
            <List dense>
              {logs.map((log, index) => (
                <ListItem key={index} sx={{ py: 0.5 }}>
                  <ListItemText primary={log} />
                </ListItem>
              ))}
            </List>
          )}
          <div ref={logsEndRef} />
        </Box>
      </Paper>
      
      {/* 已下载文件列表 */}
      {downloadedFiles.length > 0 && (
        <Paper elevation={3} sx={{ p: 3 }}>
          <Typography variant="h5" component="h2" gutterBottom>
            已下载文件 ({downloadedFiles.length})
          </Typography>
          <List>
            {downloadedFiles.map((file, index) => (
              <ListItem key={index} divider={index < downloadedFiles.length - 1}>
                <ListItemText 
                  primary={file.split('/').pop()} 
                  secondary={file} 
                />
              </ListItem>
            ))}
          </List>
        </Paper>
      )}
    </Container>
  );
}
